package com.kkks.spring_rest.tick.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.ListOrderedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.kkks.spring_rest.tick.component.BaseComponent;
import com.kkks.spring_rest.tick.dao.HibernateTemplateBaseDao;
import com.kkks.spring_rest.tick.model.User;
import com.kkks.spring_rest.tick.model.WhoComment;
import com.kkks.spring_rest.tick.model.WhoGoods;
import com.kkks.spring_rest.tick.model.WhoGoodsCommentMessage;
import com.kkks.spring_rest.tick.model.WhoSkuRelation;
import com.kkks.spring_rest.tick.model.WhoUserAddress;
import com.kkks.spring_rest.tick.model.WhoUserBaseInfo;
import com.kkks.spring_rest.tick.model.WhoUserRank;
import com.kkks.spring_rest.tick.model.WhoUsers;
import com.kkks.spring_rest.tick.model.pojo.WhoCommentList;
import com.kkks.spring_rest.tick.model.pojo.WhoUserLogin;
import com.kkks.spring_rest.tick.service.UserService;
import com.kkks.spring_rest.tick.utils.ConvertHelper;
import com.kkks.spring_rest.tick.utils.DateHelper;
import com.kkks.spring_rest.tick.utils.PasswordParseHelper;
import com.kkks.spring_rest.tick.utils.ThreeDESHelper;

/**
 * @author SC
 * @version 1.0
 * @created 2012-7-19 上午9:48:48
 * @describe 用户管理实现类
 */
@Service
@Transactional
@SuppressWarnings("rawtypes")
public class UserServiceImpl implements UserService {

	@Autowired
	private HibernateTemplateBaseDao hibernateTemplateBaseDao;

	@Autowired
	private BaseComponent baseComponent;

	public HibernateTemplateBaseDao getHibernateTemplateBaseDao() {
		return hibernateTemplateBaseDao;
	}

	public void setHibernateTemplateBaseDao(
			HibernateTemplateBaseDao hibernateTemplateBaseDao) {
		this.hibernateTemplateBaseDao = hibernateTemplateBaseDao;
	}

	public BaseComponent getBaseComponent() {
		return baseComponent;
	}

	public void setBaseComponent(BaseComponent baseComponent) {
		this.baseComponent = baseComponent;
	}

	/**
	 * 生成userToken
	 * 
	 * @param user
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
	private String getUserToken(WhoUsers user) {
		String origionStr = user.getUserName() + user.getUserId();
		return ThreeDESHelper.encryptMode(origionStr);
	}

	/**
	 * 描述 用户登录类
	 * 
	 * @param username
	 * @param password
	 * @return WhoUserLogin
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false, rollbackFor=Exception.class)
	public WhoUserLogin UserLogin(String userName, String password) {// TODO
		WhoUserLogin whoUserLogin = new WhoUserLogin();
		try {
			WhoUsers whoUsers = getUserByUserName(userName);
			if (whoUsers != null) {// 用户存在，判断密码
				if (PasswordParseHelper.isSamePassword(password, whoUsers
						.getWhoUserBaseInfo().getPassword())) {// 密码正确
					WhoUserRank whoUserRank = (WhoUserRank) this.hibernateTemplateBaseDao
							.findTByHql("from WhoUserRank where rankId = ? ",
									new Object[] { whoUsers.getUserRank() });

					whoUserLogin.setUserId(whoUsers.getUserId());
					whoUserLogin.setUserName(whoUsers.getUserName());
					// 设置UserToken,使用userName + userId
					whoUserLogin.setUserToken(getUserToken(whoUsers));
					whoUserLogin.setUserLevel(whoUserRank.getRankName());
					whoUserLogin.setDiscount(String.valueOf(whoUserRank
							.getDiscount()));
					whoUserLogin.setBalance(String.valueOf(whoUsers
							.getWhoUserBaseInfo().getUserBalance()));
					WhoUserAddress whoUserAddress = (WhoUserAddress) this.hibernateTemplateBaseDao
							.findTByHql(
									" from WhoUserAddress where addressId = ? ",
									whoUsers.getAddressId());
					whoUserLogin.setWhoUserAddresses(whoUserAddress);

					whoUserLogin.setReturnValue("1");
					whoUserLogin.setErrorDescription("登录成功");
				} else {// 密码错误
					whoUserLogin = new WhoUserLogin("", "", "", "", "",
							new WhoUserAddress(), "0", "密码错误");
				}
			} else {// 用户不存在
				whoUserLogin = new WhoUserLogin("", "", "", "", "",
						new WhoUserAddress(), "0", "用户不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return whoUserLogin;
	}

	/**
	 * 描述 根据用户名获取用户信息
	 * 
	 * @param username
	 * @param password
	 * @return WhoUsers
	 */
	@Override
	public WhoUsers getUserByUserName(String userName) {// TODO
		try {
			WhoUsers whoUsers = (WhoUsers) this.hibernateTemplateBaseDao
					.findTByHql(
							" from WhoUsers where userName = ? or email = ?",
							new Object[] { userName, userName });
			if (whoUsers != null) {
				return whoUsers;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 描述 用户注册
	 * 
	 * @param userName
	 * @param password
	 * @param confirm
	 * @param phoneType
	 *            //10 iphone 12 android 11 ipad 默认 0 mobile
	 * @return resultValue int 0失败;1成功 errorDescription
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Map UserRegister(String userName, String password, String confirm,
			String phoneType) {// TODO
		ListOrderedMap map = new ListOrderedMap();
		try {
			if (!password.equals(confirm)) {// 密码输入不一致
				map.put("resultValue", 0);
				map.put("errorDescription", "密码输入不一致");
			} else {
				if (this.getBaseComponent().isExistUserNameEmail(userName)) {// 用户名存在
					map.put("resultValue", 0);
					map.put("errorDescription", "用户名已存在!");
				} else {// 用户名不存在，密码与确认密码一致
					// 用户信息
					WhoUsers user = new WhoUsers();
					user.setUserName(userName);
					user.setEmail(userName);
					user.setAvatar("");
					user.setQuestion("");
					user.setAnswer("");
					user.setSex(true);
					user.setBirthday(DateHelper.getCurrentDate());
					user.setAddressId(0);
					user.setUserRank((short) 1);
					user.setParentId(0);
					user.setAlias("");
					user.setMsn("");
					user.setOfficePhone("");
					user.setHomePhone("");
					user.setMobilePhone("");
					user.setIsValidated((short) 0);
					user.setCreditLine((double) 0);
					user.setYahoo("");
					user.setSkype("");
					user.setCountry("");
					user.setIsGoogle(0);

					if (phoneType != null) {
						if (phoneType.equals("10")) {
							user.setIsGoogle(10);
						} else if (phoneType.equals("11")) {
							user.setIsGoogle(11);
						} else if (phoneType.equals("12")) {
							user.setIsGoogle(12);
						}
					} else {
						user.setIsGoogle(0);
					}
					user.setAvatar("avatar");
					user.setGoodsComment((short) 0);

					// 用户基本信息
					WhoUserBaseInfo userBaseInfo = new WhoUserBaseInfo();
					userBaseInfo.setEmail(userName);
					userBaseInfo.setIsVip(true);
					userBaseInfo.setLastIp((long) 0);
					userBaseInfo.setLastLogin(0);
					userBaseInfo.setLastPaymentId(0);
					userBaseInfo.setLastShippingId(0);
					userBaseInfo.setManagerId(0);
					userBaseInfo.setPassword(PasswordParseHelper
							.getEncryptPassword(password));
					userBaseInfo.setPayPoints(0);
					userBaseInfo.setRankPoints(0);
					userBaseInfo.setRegIp((long) 0);
					userBaseInfo.setRegTime(ConvertHelper.DateToInt(DateHelper
							.getCurrentDate()));
					userBaseInfo.setUserBalance((double) 0.0);
					userBaseInfo.setUserName(userName);
					userBaseInfo.setUserRank(false);
					userBaseInfo.setVisitCount(0);
//					userBaseInfo.setWhoUsers(user);

					user.setWhoUserBaseInfo(userBaseInfo);
					this.hibernateTemplateBaseDao.save(user);
					map.put("resultValue", 1);
					map.put("errorDescription", "注册成功");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			new Throwable("用户注册失败");
			map.put("resultValue", 0);
			map.put("errorDescription", "网络忙碌");
		}
		return map;
	}

	/**
	 * 描述 新增用户评论
	 * 
	 * @param userId
	 * @param goodsId
	 * @param userToken
	 * @param title
	 * @param content
	 * @return ListOrderedMap
	 */
	@SuppressWarnings("unchecked")
	@Override
	public ListOrderedMap AddGoodsComment(String goodsId, String userId,
			String userToken, String title, String content) {// TODO
		ListOrderedMap map = new ListOrderedMap();
		WhoGoodsCommentMessage whoGoodsCommentMessage = new WhoGoodsCommentMessage();

		try {
			WhoGoods whoGoods = (WhoGoods) this.hibernateTemplateBaseDao
					.findTByHql("from WhoGoods where goodsId = ?",
							new Object[] { Integer.parseInt(goodsId) });
			WhoSkuRelation whoSkuRelation = (WhoSkuRelation) this.hibernateTemplateBaseDao
					.findTByHql("from WhoSkuRelation where goodsId = ?",
							new Object[] { Integer.parseInt(goodsId) });
			WhoUsers whoUsers = (WhoUsers) this.hibernateTemplateBaseDao
					.findTByHql("from WhoUsers where userId = ?",
							new Object[] { Integer.parseInt(userId) });

			if (this.baseComponent.validUserToken(userId, userToken)) {
				whoGoodsCommentMessage.setGoodsId(Integer.valueOf(goodsId));
				whoGoodsCommentMessage.setGoodsName(whoGoods.getGoodsName());
				whoGoodsCommentMessage.setGoodsAttr(whoSkuRelation.getSkuId());
				whoGoodsCommentMessage.setUserId(whoUsers.getUserId());
				whoGoodsCommentMessage.setUserName(whoUsers.getUserName());
				whoGoodsCommentMessage.setTitle(title);
				whoGoodsCommentMessage.setContent(content);
				whoGoodsCommentMessage.setIpAddress("mobile");
				whoGoodsCommentMessage.setStatus(false);
				whoGoodsCommentMessage.setAddTime(ConvertHelper
						.DateToInt(DateHelper.getCurrentDate()));

				this.hibernateTemplateBaseDao.save(whoGoodsCommentMessage);
				map.put("retValue", 1);
				map.put("errorDescription", "评论成功");
			} else {
				map.put("retValue", 0);
				map.put("errorDescription", "您无评论权限");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("retValue", 0);
			map.put("errorDescription", "评论失败");
		}
		return map;
	}

	/**
	 * 描述 获得用户的所有评论
	 * 
	 * @param userId
	 * @param userToken
	 * @param pageNum
	 * @return List<WhoCommentList>
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<WhoCommentList> getMyAllComments(String userId,
			String userToken, int pageNum) {// TODO
		List<WhoCommentList> result = new ArrayList<WhoCommentList>();
		String rowNum = "20";

		try {
			if (this.baseComponent.validUserToken(userId, userToken)) {
				List<Object[]> temp = this.hibernateTemplateBaseDao
						.findPaginationListByHql(
								"SELECT c,g from WhoComment c, WhoGoodsCommentMessage g WHERE  c.userId = ? AND  g.goodsId = c.idValue",
								Integer.parseInt(rowNum) * (pageNum - 1),
								Integer.parseInt(rowNum),
								new Object[] { Integer.parseInt(userId) });
				int pageCount = (int) Math.ceil(Double.valueOf(temp.size()) / 20);
				
				for (int i = 0; i < temp.size(); i++) {
					WhoComment whoComment = (WhoComment) temp.get(i)[0];
					WhoGoodsCommentMessage whoGoodsCommentMessage = (WhoGoodsCommentMessage) temp
							.get(i)[1];
					WhoCommentList whoCommentList = new WhoCommentList();
					
					whoCommentList.setCommentId(whoComment.getCommentId());
					whoCommentList.setGoodsId(whoComment.getIdValue());
					whoCommentList.setGoodsName(whoGoodsCommentMessage
							.getGoodsName());
					whoCommentList.setGoodsAttr(whoGoodsCommentMessage
							.getGoodsAttr());
					whoCommentList.setUserId(whoComment.getUserId());
					whoCommentList.setUserName(whoComment.getUserName());
					whoCommentList.setTitle(whoGoodsCommentMessage.getTitle());
					whoCommentList.setContent(whoComment.getContent());
					whoCommentList.setStatus(whoComment.getStatus());
					whoCommentList.setAddTime(whoComment.getAddTime());
					
					whoCommentList.setPageCount(String.valueOf(pageCount));
					whoCommentList.setRowNum(rowNum);
					result.add(whoCommentList);
				}
			} else {
				result = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			new Thread("获得用户的所有评论异常");
		}
		return result;
	}

	/**
	 * 描述 设置默认收货地址
	 * 
	 * @param userId
	 * @param userToken
	 * @param addressId
	 * @return ListOrderedMap
	 */
	@SuppressWarnings("unchecked")
	@Override
	public ListOrderedMap setDefaultAddress(String userId, String userToken,
			String addressId) {// TODO 
		ListOrderedMap map = new ListOrderedMap();
		try {
			if(this.baseComponent.validUserToken(userId, userToken)){
				WhoUsers whoUsers = (WhoUsers) this.hibernateTemplateBaseDao
						.findTByHql(" from WhoUsers where userId = ? ",
								new Object[] { Integer.parseInt(userId) });
				whoUsers.setAddressId(Integer.parseInt(addressId));
				this.hibernateTemplateBaseDao.saveOrUpdate(whoUsers);
				
				map.put("retValue", 1);
				map.put("errorDescription", "设置成功");
			}else{
				map.put("retValue", 0);
				map.put("errorDescription", "没有权限");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("retValue", 0);
			map.put("errorDescription", "设置失败");
		}
		return map;
	}

	
	@SuppressWarnings("unchecked")
	public List getAllUsers(){
		return this.hibernateTemplateBaseDao.findAll(WhoUsers.class);
	}
	
	@SuppressWarnings("unchecked")
	public void addOrUpdate(WhoUsers user){
		this.hibernateTemplateBaseDao.saveOrUpdate(user);
	}
	
	@SuppressWarnings("unchecked")
	public void deleteUsers(List<Integer> usersId){
		if(usersId != null && usersId.size() > 0) {
			for (Integer id : usersId) {
				this.hibernateTemplateBaseDao.deleteObjectById(WhoUsers.class, id);
			}
		}
	}
}
